/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.ix.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ix.data.entities.PeerInfo;
import org.ix.data.manager.P2PBroker;
import org.ix.data.manager.POJOManager;
import org.ix.data.models.Items;
import org.ix.data.models.Items.Item;
import org.ix.utils.Network;
import org.ix.utils.Serialize;

public class Test extends BaseLocalServlet {

    public String getServletInfo() {
        return "Test servlet";
    }

    protected void serve(HttpServletRequest req, HttpServletResponse res) {
        String remoteAddress = req.getRemoteAddr(); // IP
        String remoteHost = req.getRemoteHost(); // hostname

        P2PBroker broker = (P2PBroker) getServletContext().getAttribute(prop("p2pBrokerSessionName"));
        if (broker == null) {
            broker = (P2PBroker) Serialize.readFromFile(prop("dataDir") + prop("p2pBrokerFileName"));
            if (broker == null) {
                broker = new P2PBroker();
            }
        }
        PeerInfo testPeer = new PeerInfo("noid[" + remoteHost + "]", remoteAddress, req.getRemotePort());
        broker.addPeer(testPeer);

        out.println("<h3>Servlet Test at " + req.getContextPath() + "</h3>");
        out.println("<p>properties <b>appname: " + prop("appname") + "</b></p>");
        out.println("<p>attribute <b>peers: " + broker.toString() + "</b></p>");
        out.println("<p>" + lbl("p2p.ipaddress") + ": <b> " + remoteAddress + "</b></p>");
        out.println("<p>" + lbl("p2p.host") + ": <b>: " + remoteHost + "</b></p>");
        String serverName = req.getServerName();
        String servletPath = req.getServletPath();
        int serverPort = req.getServerPort();
        out.println("<p>server name: <b>: " + serverName + "</b></p>");
        out.println("<p>server port: <b>: " + serverPort + "</b></p>");
        out.println("<p>servlet path: <b>: " + servletPath + "</b></p>");
        out.println("<p>extern IP: <b>: " + URLParse() + "</b></p>");
        
        out.print("<br/><pre>");
        out.print(Network.displayInterfaceInformation());
        out.print("</pre>");

        out.println("<pre>");
        try {
            out.println(exec());
        } catch (Exception exc) {
            out.println(exc.getMessage());
        }
        out.println("</pre>");
        Item item = new Item();
        item.idescr = "test";
        item.ipkid = new Long(3);
        out.println("<pre>");
        out.println(POJOManager.createQuery("ITEMS", item, POJOManager.SQL_INSERT) + "\n");
        out.println(POJOManager.createQuery("ITEMS", item, POJOManager.SQL_UPDATE) + "\n");
        out.println(POJOManager.createQuery("ITEMS", item, POJOManager.SQL_DELETE) + "\n");
        out.println("</pre>");
        out.println("</body>");
        out.println("</html>");
        getServletContext().setAttribute(prop("p2pBrokerSessionName"), broker);
        if(req.getParameter("write")!=null) {
            Serialize.writeToFile(broker, prop("dataDir") + prop("p2pBrokerFileName"));
        }
    }

    public String exec() throws SQLException, ClassNotFoundException {
        Connection cnn = (Connection) getServletContext().getAttribute("connection");
        Items itemsManager = new Items(cnn);
        ArrayList<Items.Item> items = itemsManager.loadItems(null);

        String values = "";
        Iterator<Items.Item> iterItems = items.iterator();
        while (iterItems.hasNext()) {
            Item item = iterItems.next();
            values += item.name;
            values += ", ";
            values += item.val;
            values += ", ";
            values += item.idescr;
            values += ", ";
            values += item.dtcreate;
            values += ", ";
            values += item.dtupdate;
            values += ", ";
            values += item.ifktype;
            values += "\n";
        }
        return values;
    }

    /**
     * Connect to a remote file that return the IP address of this application
     *
     * @return String IP address
     */
    private String URLParse() {
        String html = "";

        try {
            URL remoteSite = new URL(prop("ipresolver"));
            URLConnection connection = remoteSite.openConnection();
            BufferedReader brInput = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;

            if ((inputLine = brInput.readLine()) != null) {
                html += inputLine;
            }
            brInput.close();
            /*
             * InetAddress netAddress = null; if
             * (req.getHeader("x-forwarded-for") != null) { netAddress =
             * InetAddress.getByName(req.getHeader("x-forwarded-for")); } else {
             * netAddress = InetAddress.getByName(req.getServerName()); }
             *
             * String ip = netAddress.getHostAddress();
             */
        } catch (Exception genexc) {
            html = "";
        }

        return html;
    }
}
